<template>
  <div class="employees-container">
    <div class="app-container">

      <page-tools>
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="头像" prop="staffPhoto" sortable="">
            <template v-slot="{row}">
              <img
                v-if="row.staffPhoto||imgs"
                v-errorimg="imgs"
                :src="row.staffPhoto"
                width="75px"
                height="75px"
                @click="clickShowCodeDialog(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" prop="mobile" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ timeOfEntry(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件             :current-page="page"
            :page-size="pageSize" -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :total="total"
            layout="prev, pager, next"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <add-employee :show-dialog.sync="showDialog" />

      <!-- 生成二维码弹窗 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog" width="300px">
        <el-row type="flex" justify="center">
          <canvas ref="canvas" />
        </el-row>
      </el-dialog>

      <AssignRole :show-role-dialog.sync="showRoleDialog" />
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import dayjs from 'dayjs'
import addEmployee from './components/add-employee.vue'
import imgs from '@/assets/common/head.jpg'
import qrcode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employees',
  components: { addEmployee, AssignRole },
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      showDialog: false, // 弹窗
      imgs,
      showCodeDialog: false, // 生成二维码弹窗

      showRoleDialog: false, // 角色权限弹窗

      userId: '' // 角色ID
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取数据
    async getEmployeeList() {
      const { data: { rows, total }} = await reqGetEmployeeList(this.page, this.size)
      this.list = rows
      this.total = total
    },
    // 分页函数
    handleCurrentChange(newPage) {
      this.page = newPage
      this.getEmployeeList()
    },
    // 根据id来判断聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === +cellValue)
      return obj ? obj.value : '未入职'
    },
    // 格式化时间
    timeOfEntry(time) {
      return dayjs(time).format('YYYY年MM月DD日')
    },
    // 删除功能
    async delEmployee(id) {
      const ress = await this.$confirm('确定删除吗?', '提示').catch(error => error)
      if (ress !== 'confirm') return
      if (this.list.length === 1 && this.page > 1) this.page--
      const res = await reqDelEmployee(id)
      this.$message.success(res.message)
      this.getEmployeeList()
    },
    // 导出员工
    async handleDownload() {
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { data: { rows }} = await reqGetEmployeeList(1, this.total)
      const arr = []
      rows.forEach(item => {
        const nweArr = []
        headersArr.forEach(key => {
          const enKey = headersRelations[key]
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            item[enKey] = this.timeOfEntry(item[enKey])
            console.log(item[enKey])
          }
          if (enKey === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(value => value.id === +item[enKey])
            nweArr.push(obj ? obj.value : '未知')
          } else {
            nweArr.push(item[enKey])
          }
        })
        arr.push(nweArr)
      })
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: arr, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 点击图片生成二维码
    clickShowCodeDialog(data) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        qrcode.toCanvas(this.$refs.canvas, data)
      })
    },
    // 点击角色弹出框
    editRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style>

</style>
